<!-- 沟通记录编辑 -->
<template>
  <div @touchmove="touchmove">
    <van-calendar
      :show-confirm="false"
      v-model="ShowAccountingEndDate"
      @confirm="EndTime"
    />
    <van-popup
      v-model="show"
      position="left"
      class="fa"
      :style="{ height: '100%', width: '100%' }"
    >
      <div>
        <van-nav-bar
          :title="title + '沟通记录'"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
        <van-form
          ref="checkform"
          @submit="onSubmit"
          style="height: 100%; overflow: auto; box-sizing: border-box"
        >
          <div class="client" style="padding-bottom: 70px">
            <van-field
              :rules="[{ required: true, message: '请填写客户名' }]"
              :disabled="disabled"
              @click="CustomerChoice"
              label="客户名称："
              right-icon="edit"
              v-model="entity.CustomerName"
              placeholder="请选择客户"
            >
            </van-field>
            <van-field
              :disabled="disabled"
              :rules="[{ required: true, message: '请选择日期' }]"
              label="日期："
              placeholder="请选择日期"
              :value="entity.DailyRecordDate"
              @click="DailyRecordClick"
            />
            <van-field
              :disabled="disabled"
              :rules="[{ required: true, message: '请输入标题' }]"
              label="标题："
              v-model="entity.DailyRecordTitle"
            >
            </van-field>
            <van-field
              :disabled="disabled"
              label="关键字："
              placeholder="请使用【回车】分词"
              @keydown.enter.stop="down"
              v-model="keyword"
            >
            </van-field>
            <van-tag
              type="primary"
              v-for="(item, index) in WordList"
              :key="index"
              closeable
              class="tagClass"
              @close="closeTag(index)"
              >{{ item }}</van-tag
            >
            <van-field
              v-if="title == '新建'"
              :disabled="disabled"
              :rules="[{ required: true, message: '请输入交流内容' }]"
              label="交流内容:"
              v-model="entity.DailyRecord"
              type="textarea"
              placeholder="请输入交流内容"
              rows="1"
            >
            </van-field>
            <div
              v-else
              style="
                padding: 10px 16px;
                color: #c8c9cc;
                font-size: 16px;
                display: flex;
                width: 100%;
              "
            >
              <div style="width: 86px; margin-right: 12px">交流内容：</div>
              <div
                style="font-size: 14px; font-family: tahoma, arial"
                v-html="entity.DailyRecord"
              ></div>
            </div>
            <!-- <quill-editor
            v-else
            class="editor"
            v-model="entity.DailyRecord"
            ref="myQuillEditor"
            @blur="onEditorBlur"
            @focus="onEditorFocus"
            @ready="onEditorReady"
          >
          </quill-editor> -->
            <van-field label="附件">
              <template #input>
                <!-- 考虑到除了新增，修改时也要用到这个页面，且只有单张照片，而且数据库里直接存的路径，在这里可以展示一下已经上传的图片，也可以做点击预览 -->
                <!-- <van-image
                :src="entity.reportPic"
                fit="contain"
                v-if="entity.reportPic != ''"
              /> -->
                <!-- 图片选择，上传前判断格式，删除前做数据处理  -->
                <!-- 图片选择，上传前判断格式，删除前做数据处理  -->
                <van-uploader
                  :disabled="disabled"
                  v-model="fileList"
                  :after-read="afterRead"
                  :before-delete="beforeDelete"
                  :max-count="1"
                />
              </template>
            </van-field>
          </div>
          <!-- <div class="scrollBar">
          </div> -->
        </van-form>
        <div v-show="hideshow">
          <div class="submitButton" v-if="!disabled">
            <div >
              <van-button
                @click="buttonSubmitChange"
                round
                block
                type="info"
                native-type="submit"
                >提交</van-button
              >
            </div>
          </div>
        </div>
      </div>
      <Myuser @customerChoice="Client" ref="myuser" />
      <Product @Product="Product" ref="product" />
      <!-- <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '5px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <van-button @click="close" slot="button" type="default"
          >关闭</van-button
        >
        <van-button
          v-if="!disabled"
          @click="handleSubmit"
          slot="button"
          type="primary"
          >保存</van-button
        >
      </div> -->
    </van-popup>
  </div>
</template>

<script>
import { Icon } from "vant";
import { Popup } from "vant";
import { AddressList } from "vant";

import {
  Row,
  Col,
  Cell,
  CellGroup,
  Toast,
  NavBar,
  Divider,
  Image,
  Uploader,
} from "vant";
import { Field, Calendar } from "vant";
//客户
import Myuser from "@/components/OwnUser.vue";
import Product from "../../components/Product.vue";
export default {
  props: {
    parentObj: Object,
    // readonly: { type: Boolean, required: false }
  },
  components: {
    "van-calendar": Calendar,
    //分割线
    "van-divider": Divider,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    "van-image": Image,
    "van-uploader": Uploader,
    Myuser,
    Product,
  },
  data() {
    return {
      // 解决表单输入移动端键盘弹起导致的页面fixed定位元素布局错乱问题
      docmHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      showHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      // 按钮是否禁用
      disabled: false,
      // 上传附件列表数据
      fileList: [
        { url: "" },
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
        // { url: "https://cloud-image", isImage: true }
      ],
      title: "编辑",
      readonly: false,
      WordList: [],
      // 关键字
      keyword: "",
      entity: {
        reportPic: "",
      },
      data: [],
      ShowAccountingEndDate: false,
      show: false,
      Id: "",
      messages: [],
      info: "",
      thumbUrl: "",
      isReadonly: false,
    };
  },
  created() {
    this.$route.query.Id ? (this.Id = this.$route.query.Id) : "";
    // this.title = this.$route.query.readonly == 1 ? this.title = '查看' : this.title = '编辑';
    // 判断是编辑还是查看详情
    if (this.$route.query.readonly == 0) {
      // 新建
      this.title = "新建";
      // 显示提交按钮
      this.disabled = false;
      this.isReadonly = true;
    } else if (this.$route.query.readonly == 1) {
      this.title = "编辑";
      // 编辑
      // 显示提交按钮
      this.disabled = false;
      this.isReadonly = true;
    } else {
      // 查看
      this.title = "查看";
      this.readonly = true;
      this.disabled = true;
    }

    this.readonly = this.$route.query.readonly == 1 ? true : false;
    console.log();
    console.log(this.$route.query);
    this.openForm(JSON.parse(sessionStorage.getItem("item")));
    // 只有查看的时候调用接口
    // 获取沟通记录详情
    this.GetTheDataDetail(this.Id);
  },
  watch: {
    //监听显示高度
    showHeight: function () {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    },
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };
  },
  methods: {
    // 上传名片
    //图片选择后回调，这里就是重点了，就是在选择照片后，将照片的信息封装到FormData对象中
    //注意我这里是单图上传，所以直接new了，如果是多图的话，应该要考虑添加和删除FormData中的元素
    afterRead(file) {
      //创建FormData对象。上传图片需要转换二进制，这里要用到FormData
      let forms = new FormData();
      //"file"表示给后台传的属性名字
      forms.append("file", file.file); //获取上传图片信息
      this.fileListData = file;
      file.status = "uploading";
      file.message = "上传中...";
      this.reportPicUpload(forms, file);
    },
    //图片删除前回调，删除时将公共变量forms中的文件信息一并删除
    beforeDelete(forms, file) {
        forms = null;
      this.thumbUrl= ''
      this.entity.File = []
      this.entity.SDRDTOList=[]
      // this.fileListData=[]
      return true;
    },
    //图片上传，由提交按钮调用本方法实现手动上传
    reportPicUpload(params, file) {
      //如果文件列表为空，则不需要调用上传
      if (params == null || params.length == 0) {
        return;
      }
      this.http
        .post(
          "/CustomerManagement/Cust_CustomerLinkMan/UploadFileByForm",
          params
        )
        .then((res) => {
          
          Toast.success("已上传");
          file.status = "done";
          if (res.thumbUrl) {
            this.$set(this.entity, "BusinessCardURL", res.thumbUrl);
            this.thumbUrl = res.thumbUrl;
            let obj={
              FileURL: this.thumbUrl
            }
            this.entity.SDRDTOList[0] = obj
            this.entity.File[0] = this.thumbUrl
            
          } else {
            Toast.fail(res.msg);
          }
        })
        .catch((err) => {
          Toast.fail("图片上传失败");
          setTimeout(() => {
            file.status = "failed";
            file.message = "上传失败";
          }, 1000);
        });
    },

    // 获取沟通记录详情
    GetTheDataDetail(ID) {
      this.http
        .post("/CustomerManagement/SalesmanDailyRecord/GetTheData", {
          id: ID,
        })
        .then((res) => {
          
          if (res.Success) {
            this.entity = res.Data;

            this.$set(this.entity, "File", []);
           

            // 时间格式化 去掉末尾的000
            this.entity.DailyRecordDate = this.entity.DailyRecordDate.replace(
              ".000",
              ""
            );
            // 渲染关键字
            this.WordList = res.Data.DRKeyWordList;
            // 渲染图片
            if (res.Data.SDRDTOList.length !== 0) {
              this.entity.reportPic = res.Data.SDRDTOList[0].FileURL;
              this.fileList[0].url = res.Data.SDRDTOList[0].FileURL;
              this.thumbUrl = res.Data.SDRDTOList[0].FileURL;
            }

            console.log('获取图片上传信息', res, this.thumbUrl)
          } else {
            Toast(res.Msg);
          }
        });
    },
    swipeleft() {
      this.show = false;
      // alert("123");
    },
    touchstart(e) {
      // alert("123");

      e.preventDefault();

      this.startX = e.touches[0].clientX;
      this.startY = e.touches[0].clientY;
    },
    touchmove(e) {
      //    this.show = false;
      e.preventDefault();
      this.moveX = e.touches[0].clientX;
      this.moveY = e.touches[0].clientY;
      // this.startX - this.moveX <= 0
      //   ? console.log("你在往右滑")
      //   : console.log("你在往左滑");
    },

    closeTag(index) {
      if (this.disabled == false) {
        console.log(index);
        this.WordList.splice(index, 1);
      }
    },
    down() {
      if (this.disabled == false) {
        if (!this.WordList) {
          this.WordList = [];
        }
        console.log(this.keyword);
        console.log(this.WordList);
        let a = this.WordList.includes(this.keyword);
        if (!a && this.keyword != "") {
          this.WordList.push(this.keyword);
        } else {
          Toast.fail("关键字不能重复或者为空");
        }
        this.keyword = "";
      }
    },
    onEditorBlur() {
      console.log("blur", this.messages);
    },

    onEditorFocus() {
      console.log("focus", this.messages);
    },

    onEditorReady() {
      console.log("ready", this.messages);
    },

    formatDate(date) {
      var time = new Date(date);
      var y = time.getFullYear();

      return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    DailyRecordClick() {
      if (this.disabled == false) this.ShowAccountingEndDate = true;
    },
    EndTime(date) {
      // 时间
      let myDate = new Date();
      var h =
        myDate.getHours() < 10 ? "0" + myDate.getHours() : myDate.getHours();
      var minute =
        myDate.getMinutes() < 10
          ? "0" + myDate.getMinutes()
          : myDate.getMinutes();
      var s =
        myDate.getSeconds() < 10
          ? "0" + myDate.getSeconds()
          : myDate.getSeconds();
      let time = h + ":" + minute + ":" + s;

      this.entity.DailyRecordDate = this.formatDate(date) + " " + time;
      this.ShowAccountingEndDate = false;
    },
    //返回
    onClickLeft() {
      this.show = false;
      this.$router.go(-1);
      // console.log(this.$parent);
      // this.$parent.getDataList();
    },
    //选中的产品
    Product(a) {
      console.log(a, "选择产品信息");

      this.data.push({
        ProductId: a.cInvCode,
        cInvName: a.cInvName,
        cInvCode: a.cInvCode,
        cInvStd: a.cInvStd,
      });
    },

    close() {
      this.show = false;
      this.entity = {};
      // this.$parent.getDataList();
      this.$router.go(-1);
    },
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);

      this.entity.CustomerId = a.cCusCode;
    },
    //选择客户
    CustomerChoice() {
      if (this.$route.query.readonly == 0 || this.$route.query.readonly == 1) {
        this.$refs.myuser.openForm();
      }
    },
    getDataList() {
      this.http
        .post("/QuotationManagement/Quot_OfferSheetMain/GetTheDataOfAll", {
          SortField: "Id",
          SortType: "desc",
          Search: {
            Condition: "Id",
            Keyword: this.Id,
          },
        })
        .then((res) => {
          if (res.Success) {
            // this.entity = res.Data;
            this.data = res.Data.QOSD_List;
          } else {
            Toast(res.Msg);
          }
        });
    },
    init() {
      this.show = true;
      this.data = [];
      this.WordList = [];
      this.entity = {};
      this.$set(this.entity, "DailyRecord", "");
      this.http.post("/Base_Manage/Home/GetOperatorInfo").then((resJson) => {
        this.info = resJson.Data.UserInfo;
      });
    },

    // 使用ref进行表单提交。。防止关键字输入后电脑按键回车或者手机按键回车直接提交或者跳转下一步了
    buttonSubmitChange() {
      this.$refs.checkform.submit();
    },

    onSubmit() {
      this.entity.SalesmanName = this.info.RealName;
      this.entity.DRKeyWordList = this.WordList;
      if(this.entity.reportPic===''){
        delete this.entity.reportPic
      }

    if(this.thumbUrl ===''){
      this.entity.SDRDTOList=[]
      this.entity.File=[]
    }else{
      this.entity.SDRDTOList=[]
      let obj={
          FileURL: this.thumbUrl
        }
        this.entity.SDRDTOList[0] = obj
        this.entity.File[0] = this.thumbUrl
    }




     console.log('获取提交参数',this.entity, this.thumbUrl)
      this.http
        .post("/CustomerManagement/SalesmanDailyRecord/SaveData", this.entity)
        .then((res) => {
          console.log(res);
          if (res.Success) {
            this.show = false;
            Toast.success("操作成功");
            this.$router.go(-1);
            setTimeout(() => {
              this.btnLoading = false;
            }, 500);
          } else {
            Toast(res.Msg);
          }
        });
    },
    // 打开编辑页
    openForm(row) {
      this.init();

      if (row) {
        // this.entity = row;
        this.WordList = this.entity.DRKeyWordList;
        if (this.entity.DailyRecordDate) {
          console.log(this.entity.DailyRecordDate);
          this.entity.DailyRecordDate = this.entity.DailyRecordDate.substring(
            0,
            10
          );
        }
      }
    },
  },
};
</script>

<style>
.van-field--min-height .van-field__control {
  min-height: 104px !important;
}
.scrollBar {
  height: calc(100vh - 230px);
  /* padding-bottom: 80px; */
  overflow: auto;
}
.close {
  position: "absolute";

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}
.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.box {
  width: 80%;
  height: 200px;
  overflow: auto;
  margin: 0 auto;

  border: 1px solid #ccc;
  /* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

  margin-top: 20px;
  margin-bottom: 10px;
}
.tagClass {
  color: #000;
  padding: 5px;
  background-color: #ccc;
  border-radius: 8px;
  margin-left: 5px;
  padding-left: 10px;
}
</style>
